package com.servlet;

import com.pojo.Resources;
import com.pojo.Role;
import com.pojo.User;
import com.service.ResourcesService;
import com.service.RoleService;
import com.service.impl.ResourcesServiceImpl;
import com.service.impl.RoleServiceImpl;
import com.util.BaseServlet;
import com.util.LayuiTable;
import com.util.ResultData;
import com.util.StringToIntArrayUtile;
import com.vo.ResourceId;
import com.vo.ResourcesDtree;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

@WebServlet("/role")
public class RoleServlet extends BaseServlet {

    ResourcesService resourcesService = new ResourcesServiceImpl();
    RoleService roleService = new RoleServiceImpl();
    public String getMenuBtn(HttpServletRequest request, HttpServletResponse response){
        HttpSession session = request.getSession(true);
        User user = (User)session.getAttribute("user");
        int uid=user.getId();
        int mid = Integer.parseInt(request.getParameter("mid"));
        List<Resources> resourcesList = resourcesService.findAll(uid,mid);
        session.setAttribute("resourceBtn",resourcesList);
        return "system/role/roleList";
    }


    public LayuiTable<Role> allRole(HttpServletRequest request, HttpServletResponse response){
        int page = request.getParameter("page")!=null?Integer.parseInt(request.getParameter("page")):1;
        int limit = request.getParameter("limit")!=null?Integer.parseInt(request.getParameter("limit")):10;
        LayuiTable<Role> layuiTable=roleService.findAll(page,limit);
        return layuiTable;
    }

    public LayuiTable<ResourcesDtree> MenuDtree(HttpServletRequest request, HttpServletResponse response){
        LayuiTable<ResourcesDtree> layuiTable=resourcesService.getMenuDtree();
        return layuiTable;
    }

    public List<ResourceId> menuByRoleid(HttpServletRequest request, HttpServletResponse response){
        Integer roleid = Integer.parseInt(request.getParameter("roleid"));
        List<ResourceId> all = roleService.findAllResourceId(roleid);
        return all;
    }


    public ResultData UpdateRoleMenu(HttpServletRequest request, HttpServletResponse response){
        Integer roleid = Integer.parseInt(request.getParameter("roleid"));
        String[] mIds = request.getParameterValues("array");
        int[] ints = StringToIntArrayUtile.toInt(mIds);
        int count = roleService.updateMenusByRoleId(roleid, ints);
        ResultData<User> resultData = new ResultData<User>();
        if(count>0){
            resultData.setMsg("分配成功！");
            resultData.setStatus(200);
        }
        return resultData;
    }


    @Override
    public Class<?> getServletClass() {


        return RoleServlet.class;
    }
}
